//
//  ClassViewController.m
//  A段项目,漫画
//
//  Created by dllo on 15/4/20.
//  Copyright (c) 2015年 dllo. All rights reserved.
//



#import "ClassViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"
#import "UIImageView+WebCache.h"

#import "ClassifyModel.h"
#import "ClassifyCollectionViewCell.h"

#import "ClassifyDetailedViewController.h"

#define HEIGHT  self.view.frame.size.height
#define WIDTH   self.view.frame.size.width



@interface ClassViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
// 用来装modlle的数组
@property(nonatomic, retain)NSMutableArray *classifyArray;
@property(nonatomic, retain)UICollectionView *myCollection;
@property(nonatomic, retain)UIButton *searchButton;
@property(nonatomic, retain)UITextField *searchTextfield;
@property(nonatomic, retain)NSTimer *textFieldTimer;

@end

@implementation ClassViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.classifyArray = [NSMutableArray array];
        [MidTools shareMidTools].delegate71 = self;
        //传值协议1
        [MidTools shareMidTools].delegate81 = self;
        //指明调用者
        [MidTools shareMidTools].searchID = 1;
    }
    
    [self classifydata];
    return self;
    
}
//取值
- (void)getValue1:(NSString *)mark{
    self.searchTextfield.text = mark;
}
- (void)resignFirst1{
    [self.searchTextfield resignFirstResponder];
}
//编辑状态
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //显示搜索框
    [[MidTools shareMidTools].delegate6 makeSearchMarkWithNow:[MidTools shareMidTools].isSearchMarkShow];
}
//关闭状态
- (void)textFieldDidEndEditing:(UITextField *)textField{
    //隐藏搜索框
    [[MidTools shareMidTools].delegate6 makeSearchMarkWithNow:[MidTools shareMidTools].isSearchMarkShow];
}

- (void)createSearch{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-search.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchButton:)];
    self.searchTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 2, 30)];
    self.navigationItem.titleView = self.searchTextfield;
    self.searchTextfield.layer.borderWidth = 1.5;
    self.searchTextfield.layer.cornerRadius = 10;
    self.searchTextfield.layer.borderColor = [UIColor colorWithRed:128 / 255.0 green:128 / 255.0 blue:128 / 255.0 alpha:1].CGColor;
    self.searchTextfield.userInteractionEnabled = YES;
    self.searchTextfield.delegate = self;
    UIView *paddingView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 30)];
    self.searchTextfield.leftView = paddingView1;
    self.searchTextfield.leftViewMode = UITextFieldViewModeAlways;
    self.searchTextfield.placeholder = @"请输入关键字";
}
- (void)searchButton:(UIButton *)button{
    if (![self.searchTextfield.text isEqual:@""]) {
        [self.searchTextfield resignFirstResponder];
        //用单例进行搜索
        NSString *input = self.searchTextfield.text;
        NSLog(@"%@",input);
        NSString *str = [input stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        NSString *urlStr = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Search/comicSearchListForIos/key_word/%@/listcnt/12/page/1/clientType/0/local_version/2.3.2",str];
        [[MidTools shareMidTools] searchByUrl:urlStr];
        [self.searchTextfield resignFirstResponder];
        //推
        SearchDetalisViewController *searchDL = [[SearchDetalisViewController alloc] init];
        [self.navigationController pushViewController:searchDL animated:YES];
        [searchDL release];
        //存储搜索记录
        //先判断是否有相同记录
        BOOL isExit = NO;
        for (NSString *s in [MidTools shareMidTools].searchMark) {
            if ([s isEqual:self.searchTextfield.text]) {
                isExit = YES;
            }
        }
        if (!isExit) {
            NSString *searchMark = self.searchTextfield.text;
            [[MidTools shareMidTools].searchMark addObject:searchMark];
            self.searchTextfield.text = nil;
        }
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"搜索关键字不能为空" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        [alert release];
    }
}
- (void)classifydata
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://mobilev3.ac.qq.com/Classify/comicClassifyListV2ForIos/local_version/2.3.2/channel/1001/guest_id/921199FA-97DD-457B-80FA-5A7E1D0FC7BA/uin/null" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // JOSN解析后最外层的大字典
        NSDictionary *eventDic = responseObject;
        NSMutableArray *dataArr = [eventDic objectForKey:@"data"];
        for (NSMutableDictionary *dic in dataArr) {
            ClassifyModel *classifyMo = [[ClassifyModel alloc] init];
            [classifyMo setValuesForKeysWithDictionary:dic];
            [self.classifyArray addObject:classifyMo];
            [classifyMo release];
        }
        //*******//
        
        NSLog(@"请求成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败");
    }];
}



- (void)dealloc
{
    [_classifyArray release];
    [_myCollection release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [[UIColor alloc]initWithRed:238 / 256.0 green:226 / 256.0 blue: 176 / 256.0 alpha:1.0];
    [self creatView];
    [self createSearch];
    
    self.navigationController.navigationBar.translucent = NO;
    
}

- (void)creatView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(80, 100);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 45;
    
    // 设置头部区域大小
    //  flowLayout.headerReferenceSize = CGSizeMake(200, 100);
    
    // 设置底部区域大小
    flowLayout.footerReferenceSize = CGSizeMake(200, 100);
    
    
    // 上下左右的边框
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    
    self.myCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0 ,WIDTH - 20 , HEIGHT - 49  )collectionViewLayout:flowLayout];
    
    [self.view addSubview:self.myCollection];
    self.myCollection.delegate = self;
    self.myCollection.dataSource = self;
    
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    imageView.backgroundColor = [[UIColor alloc]initWithRed:238 / 256.0 green:226 / 256.0 blue: 176 / 256.0 alpha:1.0];
    self.myCollection.backgroundView = imageView;
    self.myCollection.backgroundView.userInteractionEnabled = YES;
    //给空白处添加点击
    UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backTapAction:)];
    //打开交互
    [self.myCollection.backgroundView addGestureRecognizer:backTap];
    
    [self.myCollection registerClass:[ClassifyCollectionViewCell class] forCellWithReuseIdentifier:@"resuse"];
    
    
    [flowLayout release];
    [_myCollection release];
}
- (void)backTapAction:(UITapGestureRecognizer *)tap{
    [self.searchTextfield resignFirstResponder];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.classifyArray.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *resuse = @"resuse";
   ClassifyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:resuse forIndexPath:indexPath];
    
    //  cell.contentView.backgroundColor = [UIColor cyanColor];
    
    ClassifyModel *mo = self.classifyArray[indexPath.row];
    cell.myLabel.text = mo.classify_title;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:mo.classify_url]];
    return cell;
}


// 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击");
    ClassifyDetailedViewController *temp = [[ClassifyDetailedViewController alloc] init];
    temp.classify_id = [self.classifyArray[indexPath.row] classify_id];
    [self.navigationController  pushViewController:temp animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
